package com.zeus.dubbo.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.config.spring.ServiceBean;
import com.alibaba.dubbo.rpc.*;
import com.hengxinyongli.zeus.common.constant.TrackConstant;
import com.hengxinyongli.zeus.common.utils.NetworkInterfaceManager;
import com.zeus.dubbo.configuration.TrackAppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 提供公用的日志配置信息
 * 生产者 提供
 * 计算耗时
 * 成功/失败状态
 * 请求和返回报文
 */
@Activate(group = {Constants.PROVIDER},value = "dubboProducerFilter")
public class DubboProducerFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long beginTime = System.currentTimeMillis();
        TrackAppConfig trackAppConfig = ServiceBean.getSpringContext().getBean(TrackAppConfig.class);
        String appCode = trackAppConfig.getAppCode();
        //track id
        String trackId = RpcContext.getContext().getAttachment(TrackConstant.TRACK_ID_KEY);
        //原始调用者ip
        String ip = RpcContext.getContext().getAttachment(TrackConstant.CALL_IP_KEY);
        //原始调用方
        String callFrom = RpcContext.getContext().getAttachment(TrackConstant.CALL_FROM_KEY);
        if (logger.isDebugEnabled()) {
            logger.debug("producer srcIp {} ,callFrom {} ,trackId {} ,call time {}", ip, callFrom, trackId, System.currentTimeMillis());
        }
        RpcContext.getContext().setAttachment(TrackConstant.CALL_IP_KEY, NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
        RpcContext.getContext().setAttachment(TrackConstant.CALL_FROM_KEY, appCode);
        Result invoke = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();
        if (logger.isDebugEnabled()) {
            logger.debug("trackId {},src ip{},call from {},call remote time {} ms", trackId, ip, callFrom, endTime - beginTime);
        }
        RpcContext.getContext().clearAttachments();
        return invoke;
    }
}
